﻿using System;
using System.Collections.Generic;
using System.Text;
using CurriculumnManage.Helper;
using System.Windows.Forms;
using CurriculumnManage.DBAccess;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.IO;

namespace CurriculumnManage.Helper
{
    public class CommonFunction
    {

        public static bool CheckYear(TextBox textBox)
        {
            if (string.IsNullOrEmpty(textBox.Text.Trim()))
            {
                CommonFunction.ShowMsg("年度[2000]を入力してください。");
                textBox.Focus();
                return false;

            }
            int intYear = MyUtils.ParseToInt(textBox.Text.Trim(), 1);
            if (intYear < 2000 || intYear > 2050)
            {
                CommonFunction.ShowMsg("年度[2000]を正しく入力してください。");
                textBox.Focus();
                return false;
            }
            return true;
        }

        public static void SetYearGrade(TextBox textBox)
        {
            DateTime now = DateTime.Now;
            if (now.Month > 3)
                textBox.Text = now.Year.ToString();
            else
                textBox.Text = (now.Year - 1).ToString();
        }

        public static void SetDefaultYear(TextBox textBox)
        {
            DateTime now = DateTime.Now;
            if (now.Month > 3)
                textBox.Text = now.Year.ToString();
            else
                textBox.Text = (now.Year - 1).ToString();
        }

        public static bool CheckGrade(ComboBox cmbGrade)
        {
            if (string.IsNullOrEmpty(cmbGrade.Text.Trim()))
            {
                CommonFunction.ShowMsg("学年を選択してください。");
                cmbGrade.Focus();
                return false;
            }
            return true;
        }

        public static bool CheckSubject(ComboBox cmbSubject)
        {
            if (string.IsNullOrEmpty(cmbSubject.Text.Trim()))
            {
                CommonFunction.ShowMsg("科目を選択してください。");
                cmbSubject.Focus();
                return false;
            }
            return true;
        }

        public static void CopyData(DBContext targetDB, DBContext sourceDB, string spGetData, string tableName, string spInsertData, params object[] parameters)
        {
            SqlResult result = sourceDB.CallProcedure(spGetData, parameters);
            InserDataToTable(targetDB, result, tableName, spInsertData);
        }

        public static void InserDataToTable(DBContext DB, SqlResult result, string tableName, string spName)
        {
            if (result.DataSet.Tables.Count > 0 && result.DataSet.Tables[0].Rows.Count > 0)
            {
                DataTable dt = result.DataSet.Tables[0];
                //string sql = "select name from syscolumns where ID=object_id('" + tableName + "')";
                SqlParameter[] parameterList = DB.GetProcedureParameter(spName);
                int count = parameterList.Length;
                foreach (DataRow dr in dt.Rows)
                {
                    object[] param = new object[count];
                    for (int i = 0; i < parameterList.Length; i++)
                    {
                        if (dr[i] == DBNull.Value)
                        {
                            param[i] = null;
                            continue;
                        }
                        if (parameterList[i].DbType == DbType.String)
                        {
                            param[i] = dr[i].ToString();
                        }
                        else if (parameterList[i].DbType == DbType.Int32)
                        {
                            param[i] = MyUtils.ParseToInt(dr[i].ToString(), 0);
                        }
                        else if (parameterList[i].DbType == DbType.DateTime)
                        {
                            param[i] = MyUtils.ParseToDateTime(dr[i].ToString(), DateTime.Now);
                        }
                        else if (parameterList[i].DbType == DbType.Double)
                        {
                            param[i] = MyUtils.PareToDouble(dr[i].ToString(), 0.0);
                        }
                    }
                    DB.CallProcedure(spName, param);
                }
            }
        }

        public static void BindCombox(DataTable dt, ComboBox cmb)
        {
            DataTable tempDt = new DataTable();
            tempDt.Columns.Add("value", typeof(String));
            tempDt.Columns.Add("text", typeof(String));
            foreach (DataRow dr in dt.Rows)
            {
                tempDt.Rows.Add(dr[0].ToString(), dr[1].ToString());
            }
            cmb.DataSource = tempDt;
            cmb.DisplayMember = "text";
            cmb.ValueMember = "value";

        }

        public static string GetInitValueByKey(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        public static void ShowError(string actionName, string errorMsg)
        {
            MyLog.TraceInstance.TraceInformation(DateTime.Now.ToString() + ":" + actionName + ":" + errorMsg);
            MessageBox.Show(errorMsg, "聖マリアンナ医科大学", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void ShowMsg(string strMsg)
        {
            MessageBox.Show(strMsg, "聖マリアンナ医科大学", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static void BindStatusCombox(ComboBox cmb)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("value", typeof(String));
            dt.Columns.Add("text", typeof(String));
            dt.Rows.Add("0", "");
            dt.Rows.Add(((int)(EumnCurriLumnStatus.未入力)).ToString(), EumnCurriLumnStatus.未入力);
            dt.Rows.Add(((int)(EumnCurriLumnStatus.入力中)).ToString(), EumnCurriLumnStatus.入力中);
            dt.Rows.Add(((int)(EumnCurriLumnStatus.教育指針印刷済)).ToString(), EumnCurriLumnStatus.教育指針印刷済);
            dt.Rows.Add(((int)(EumnCurriLumnStatus.教育指針承認)).ToString(), EumnCurriLumnStatus.教育指針承認);
            dt.Rows.Add(((int)(EumnCurriLumnStatus.ＳＢＯ印刷済)).ToString(), EumnCurriLumnStatus.ＳＢＯ印刷済);
            dt.Rows.Add(((int)(EumnCurriLumnStatus.ＳＢＯ承認)).ToString(), EumnCurriLumnStatus.ＳＢＯ承認);
            cmb.DataSource = dt;
            cmb.DisplayMember = "text";
            cmb.ValueMember = "value";
        }

        public static void BindSelectedFlagCombox(ComboBox cmb)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("value", typeof(String));
            dt.Columns.Add("text", typeof(String));
            dt.Rows.Add("-1", "全て");
            dt.Rows.Add("0", "必修科目");
            dt.Rows.Add("1", "選択科目");
            cmb.DataSource = dt;
            cmb.DisplayMember = "text";
            cmb.ValueMember = "value";
        }
        public static string GetStatusText(int id)
        {
            string returnValue = EumnCurriLumnStatus.未入力.ToString();
            if (((int)(EumnCurriLumnStatus.未入力) == id))
                returnValue = EumnCurriLumnStatus.未入力.ToString();
            else if (((int)(EumnCurriLumnStatus.入力中) == id))
                returnValue = EumnCurriLumnStatus.入力中.ToString();
            else if (((int)(EumnCurriLumnStatus.教育指針印刷済) == id))
                returnValue = EumnCurriLumnStatus.教育指針印刷済.ToString();
            else if (((int)(EumnCurriLumnStatus.教育指針承認) == id))
                returnValue = EumnCurriLumnStatus.教育指針承認.ToString();
            else if (((int)(EumnCurriLumnStatus.ＳＢＯ印刷済) == id))
                returnValue = EumnCurriLumnStatus.ＳＢＯ印刷済.ToString();
            else if (((int)(EumnCurriLumnStatus.ＳＢＯ承認) == id))
                returnValue = EumnCurriLumnStatus.ＳＢＯ承認.ToString();
            return returnValue;
        }

        public static void UpLoadFile(string fileNamePath, ref string uriString, bool IsAutoRename)
        {
            string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
            string NewFileName = fileName;
            if (IsAutoRename)
            {
                NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
            }

            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
            if (!Directory.Exists(uriString))
            {
                Directory.CreateDirectory(uriString);
            }
            if (uriString.EndsWith("/") == false) uriString = uriString + "/";
            uriString = uriString + NewFileName;

            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;

            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            //FileStream fs = OpenFile();
            BinaryReader r = new BinaryReader(fs);
            byte[] postArray = r.ReadBytes((int)fs.Length);
            Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
            try
            {
                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    postStream.Close();
                    fs.Dispose();
                }
                else
                {
                    postStream.Close();
                    fs.Dispose();

                }

            }
            catch (Exception err)
            {
                uriString = "";
                postStream.Close();
                fs.Dispose();
                throw err;
            }
            finally
            {
                postStream.Close();
                fs.Dispose();
            }
        }
    }
}
